# -*- coding: utf-8 -*-
import sys

path = r"E:\code\maya\RosaCmds\RosaCmds"
if path not in sys.path:
    sys.path.append(path)
import Tools.rosa_RivetTool as rr

import maya.cmds as mc
import scripts.commonCmds as con
import scripts.curveCmds as cr
import maya.mel as mel
import rig.twoCurve as tc

reload(tc)

sel = mc.ls(sl=1)
for sl in sel:
    al = int(mc.arclen(sl) * .2)
    mel.eval('rebuildCurve -ch 0 -rpo 1 -rt 0 -end 1 -kr 0 -kcp 0 -kep 1 -kt 0 -s %s -d 3 -tol 0.01 "%s";' % (al, sl))
    tgt_crv = mc.rename(mc.duplicate(sl)[0], sl + "_tgt")
    mc.setAttr(tgt_crv + ".tz", -0.2)
    dyn_crv1 = mc.rename(mc.duplicate(sl)[0], sl + "_dyn_crv1")
    dyn_crv2 = mc.rename(mc.duplicate(tgt_crv)[0], sl + "_dyn_crv2")
    sf = mc.rename(mc.loft(dyn_crv1, dyn_crv2)[0], sl + "_loft")
    _cvs = mc.ls(sl + ".cv[*]", fl=1)
    cvs = [_cvs[0]] + _cvs[2:]
    _pat = None
    jotlist = []
    for idx in range(len(cvs)):
        t = mc.xform(cvs[idx], q=1, ws=1, t=1)
        jot = mc.createNode("joint", name="%s_%s_jot" % (sl, idx))
        mc.setAttr(jot + ".t", t[0], t[1], t[2])
        if _pat:
            mc.parent(jot, _pat)
        _pat = jot
        jotlist.append(jot)
    mc.joint(jotlist, e=True, oj="yzx", secondaryAxisOrient="zup", ch=True, zso=True)
    ctrp = None
    tp = None
    for j in jotlist:
        ctr = cr.createControl(ctrName=j.replace("_jot", "_ctrl"))
        trans = mc.createNode("transform",name = j.replace("_jot", "_trans"))
        mc.delete(mc.parentConstraint(j, ctr, mo=0))
        mc.delete(mc.parentConstraint(j, trans, mo=0))

        mc.parent(j, ctr)
        if ctrp:
            mc.parent(ctr, ctrp)
        if tp:
            mc.parent(trans,tp)
        grp = con.emptyGroup(ctr)
        tgrp = con.emptyGroup(trans)

        rr.rivet().onMesh(sf, [tgrp[1]])
        mc.connectAttr(tgrp[1]+".t",grp[1]+".t",)
        mc.connectAttr(tgrp[1]+".r",grp[1]+".r",)

        ctrp = ctr
        tp = trans
    mc.skinCluster(jotlist, sl)
    mc.skinCluster(jotlist, tgt_crv)
    tag = sl.replace("_crv", "")
    tc.TwoCurve().create(sl, tgt_crv, tag, al * 3)



for fl in mc.ls(sl=1):
    sp = mc.listConnections(fl)[0]
    cp = con.findRelatedShape(sp)
    crv = mc.listConnections(cp+".outCurve")[0]
    nn = fl.replace("_indyn","_dyn")
    mc.blendShape(crv,nn,w=[0,1])